<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>加载天地图</title>
    <link href="ol/ol.css" rel="stylesheet" type="text/css" />
    <script src="ol/ol.js" type="text/javascript"></script>
    <style type="text/css">
        html,body{
            width: 100%;
            height: 100%;
            margin:0px;
            padding:0px;
        }
        #mapCon {
            width: 100%;
            height: 100%;
        }
        .controller-box{
            position: absolute;
            top: 25px;
            left: 30%;
            z-index: 10;
        }
    </style>
</head>
<body>
    <!-- 地图容器 -->
    <div id="mapCon">
        <div class="controller-box">
            <button onclick="addHistoryTrack()">加载轨迹</button>
            <button onclick="playHistoryTrack()">轨迹回放</button>
            <button onclick="pausePlay()">暂停回放</button>
            <button onclick="continuePlay()">继续回放</button>
            <button onclick="reset()">复位</button>
            <div style="margin-top: 10px;">
                播放时定位<input type="checkbox" name="播放时定位" id="playToCenter">
                    播放速度：  慢<input type="range" name="" id="speedRange" max="3" min="1" step="1" onchange="changeRange()">快
            </div>
            
        </div>
    </div>

    <script type="text/javascript">
        var positions = [
            {
                DeviceId: "dev_01",
                lon: 122.04481,
                lat: 37.51939,
                PositionTime: "2021-06-11 10:10:00",
            },
            {
                DeviceId: "dev_01",
                lon: 122.04481,
                lat: 37.51939,
                PositionTime: "2021-06-11 10:10:02",
            },
            {
                DeviceId: "dev_01",
                lon: 122.0426,
                lat: 37.51937,
                PositionTime: "2021-06-11 10:11:17",
            },
            {
                DeviceId: "dev_01",
                lon: 122.03448,
                lat: 37.51672,
                PositionTime: "2021-06-11 10:12:18",
            },
            {
                DeviceId: "dev_01",
                lon: 122.03065,
                lat: 37.51382,
                PositionTime: "2021-06-11 10:13:17",
            },
            {
                DeviceId: "dev_01",
                lon: 122.02631,
                lat: 37.50703,
                PositionTime: "2021-06-11 10:14:17",
            },
            {
                DeviceId: "dev_01",
                lon: 122.0262,
                lat: 37.50018,
                PositionTime: "2021-06-11 10:15:16",
            }
        ];
        let pointIndex = 0;
        var animateSpeed = 1000;//默认1s移动一个点
        var historyPoint=null;
        var key = "4689fc6b9bc0fdc8c48298f751ebfb41";//天地图密钥
        var center = [122.04481,37.51939];//北京经纬度
        var vectorSource;
        var trackPoints = [];
        var map;
        var mapView;
        //初始化地图
        function initMap(){

            //ol.layer.Tile：是一个瓦片图层类，用于显示瓦片资源。
            //source是必填项，用于为图层设置来源。

            //ol.source.XYZ: 
            //创建天地图矢量图层
            var TiandiMap_vec = new ol.layer.Tile({
                title: "天地图矢量图层",
                source: new ol.source.XYZ({
                    url: "http://t{0-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + key,
                    wrapX: false
                })
            });
            //创建天地图矢量注记图层
            var TiandiMap_cva = new ol.layer.Tile({
                title: "天地图矢量注记图层",
                source: new ol.source.XYZ({
                    url: "http://t{0-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + key,
                })
            });
            //1. 实例化Map对象加载地图
            map = new ol.Map({
                //地图容器div的ID
                target: 'mapCon',
                //地图容器中加载的图层
                layers: [TiandiMap_vec, TiandiMap_cva],
                //地图视图设置
                view: new ol.View({
                    //地图初始中心点（经纬度）
                    center: center,
                    //地图初始显示级别
                    zoom: 13,
                    projection: "EPSG:4326"
                })
            });
            mapView = map.getView();
            //2.创建用于绘制轨迹线的矢量图层以及图层源
            //矢量标注的数据源
            vectorSource = new ol.source.Vector();
            //矢量标注图层
            var vectorLayer = new ol.layer.Vector({
                source: vectorSource,
                zIndex:1000,
            });
            map.addLayer(vectorLayer);
        }
        

        initMap();

        var createPointStyle = function (feature) {
            return new ol.style.Style({
                image: new ol.style.Icon(
                    ({
                        //设置图标点
                        //anchor: [0.5, 30],
                        //图标起点
                        anchorOrigin: 'top-right',
                        //指定x值为图标点的x值
                        anchorXUnits: 'fraction',
                        //指定Y值为像素的值
                        anchorYUnits: 'pixels',
                        //偏移
                        offsetOrigin: 'top-right',
                        // offset:[0,10],
                        //图标缩放比例
                        // scale:0.5,
                        //透明度
                        opacity: 1,
                        color: '#fff',
                        //size: [32,32],
                        //图标的url
                        src: 'static/img/hq.png'
                    })),
                text: new ol.style.Text({
                    //位置
                    textAlign: 'center',
                    //基准线
                    textBaseline: 'middle',
                    //文字样式
                    font: 'normal 12px 微软雅黑',
                    //文本内容
                    text: feature.values_.data.DeviceId,
                    //文本填充样式（即文字颜色）
                    fill: new ol.style.Fill({ color: '#FF0000' })
                }),
                //zIndex:1000
            });
        }

        //添加历史轨迹的拐点
        function addHistoryPoint(data) {
            let newPoint = [data.lon, data.lat];
            trackPoints.push(data);
            historyPoint = new ol.Feature({
                //几何信息
                geometry: new ol.geom.Point(newPoint),
                data:data
            });
            //设置要素的样式
            historyPoint.setStyle(createPointStyle(historyPoint));
            //将新要素添加到数据源中
            vectorSource.addFeature(historyPoint);
            if(trackPoints.length>1){
                let points = [trackPoints[trackPoints.length-1],trackPoints[trackPoints.length-2]]
                addTrackLine(points);
                //获取播放定位的选中状态
                let checkFlag = document.getElementById("playToCenter").checked
                //如果被选中，则窗口视角跟随轨迹
                if(checkFlag){
                    mapView.setCenter(newPoint);
                }
                
            }
        }

        //创建矢量标注样式
        function createMarkerStyle(feature) {
            return new ol.style.Style({
                /**{olx.style.IconOptions}类型*/
                image: new ol.style.Icon(
                    ({
                        // anchor: [0.5, 0.5],//图标的锚点,经纬度点所对应的图标的位置，默认是[0.5, 0.5]，即为标注图标的中心点位置
                        anchorOrigin: 'top-right',//锚点的偏移位置，默认是top-left，
                        anchorXUnits: 'fraction',//锚点X的单位，默认为百分比，也可以使用px
                        anchorYUnits: 'pixels',//锚点Y的单位，默认为百分比，也可以使用px
                        offsetOrigin: 'top-right',//原点偏移bottom-left, bottom-right, top-left, top-right,默认 top-left
                        // offset:[0,10],
                        //图标缩放比例
                        // scale:0.5,//可以设置该比例实现，图标跟随地图层级缩放
                        //透明度
                        opacity: 0.75,//如果想隐藏某个图标，可以单独设置该值，透明度为0时，即可隐藏，此为隐藏元素的方法之一。
                        //图标的url
                        src: 'static/img/hq.png'
                    })
                ),
                text: new ol.style.Text({
                    //位置
                    textAlign: 'center',
                    //基准线
                    textBaseline: 'middle',
                    //文字样式
                    font: '20px 宋体',
                    //文本内容
                    text: feature.get('name'),//通过设置的fature的name属性获取，也可以通过参数获取设置，此处接收 字符串 对象
                    //文本填充样式（即文字颜色），红色
                    fill: new ol.style.Fill({ color: '#ff002f' }),
                    //描边颜色，蓝色
                    stroke: new ol.style.Stroke({ color: '#0022ff', width: 1 })
                })
            });
        }
        
        //添加历史轨迹线
        function addHistoryTrack(){
            addTrackLine(positions);
        }
        //添加折线
        function addTrackLine(points){
            let linePoints = [];
            for (let i = 0; i < points.length; i++) {
                //添加点
                let newPoint = [points[i].lon, points[i].lat];
                linePoints.push(newPoint);
            }
            var lineFeature = new ol.Feature({
                geometry: new ol.geom.LineString(linePoints)
            });
            lineFeature.setStyle(new ol.style.Style({
                //填充色
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                //边线颜色
                stroke: new ol.style.Stroke({
                    color: '#ff0019',
                    width: 5
                }),
                //形状
                image: new ol.style.Circle({
                    radius: 7,
                    fill: new ol.style.Fill({
                        color: '#ffcc33'
                    })
                })
            }));
            // 注入容器
            vectorSource.addFeature(lineFeature);
        }
        //复位初始化
        function reset(){
            //移除绘制的轨迹线
            vectorSource.clear();
            pointIndex = 0;
            historyPoint = null;
            trackPoints = [];
            mapView.setZoom(13);
            mapView.setCenter(center);
        }
        /**
         * 历史轨迹落点动画
         */
        function playHistoryTrack() {
            let index = pointIndex;
            //获取滑块中设置的速度
            let rangeValue = document.getElementById("speedRange").value;
            animateSpeed = rangeValue=='1'?1500:rangeValue=='2'?1000:500;

            animateTimeOutIndex = setTimeout(function () {
                //最后一个点时，结束轨迹播放
                if (index >= positions.length) {
                    historyPoint = null;
                    trackPoints = [];
                    pointIndex = 0;
                } else {
                    //添加点

                    if (historyPoint != null) {
                        vectorSource.removeFeature(historyPoint);
                        historyPoint = null;
                        addHistoryPoint(positions[index]);
                    } else {
                        addHistoryPoint(positions[index]);
                    }
                    pointIndex++;
                    playHistoryTrack();
                }
            }, animateSpeed);
        }
        //暂停播放轨迹
        function pausePlay(){
            clearTimeout(animateTimeOutIndex);
        }
        //继续播放
        function continuePlay(){
            playHistoryTrack();
        }
    </script>
</body>
</html>
